package com.landinfo.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codahale.metrics.annotation.Timed;
import com.landinfo.domain.User;
import com.landinfo.service.DashboardConfigService;
import com.landinfo.service.UserService;
import com.landinfo.service.dto.DashboardConfigDTO;
import com.landinfo.web.rest.errors.BadRequestAlertException;
import com.landinfo.web.rest.util.HeaderUtil;
import com.landinfo.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing DashboardConfiguration.
 */
@RestController
@RequestMapping("/api")
public class DashboardConfigResource {

    private final Logger log = LoggerFactory.getLogger(DashboardConfigResource.class);

    private static final String ENTITY_NAME = "dashboardConfig";

    private final DashboardConfigService dashboardConfigService;
    private final UserService userService;

    public DashboardConfigResource(
        DashboardConfigService dashboardConfigService,
        UserService userService
    ) {
        this.dashboardConfigService = dashboardConfigService;
        this.userService = userService;
    }

    @PostMapping("/dashboard-configurations")
    @Timed
    public ResponseEntity<DashboardConfigDTO> createDashboardConfig(@RequestBody DashboardConfigDTO dashboardConfigDTO) throws URISyntaxException {
        log.debug("REST request to save DashboardConfiguration : {}", dashboardConfigDTO);
//        if (dashboardConfigDTO.getId() != null) {
//            throw new BadRequestAlertException("A new dashboardConfig cannot already have an ID", ENTITY_NAME, "idexists");
//        }
        DashboardConfigDTO result = dashboardConfigService.save(dashboardConfigDTO);
        return ResponseEntity.created(new URI("/api/dashboard-configurations/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    @PutMapping("/dashboard-configurations")
    @Timed
    public ResponseEntity<DashboardConfigDTO> updateDashboardConfig(@RequestBody DashboardConfigDTO dashboardConfigDTO) throws URISyntaxException {
        log.debug("REST request to update DashboardConfiguration : {}", dashboardConfigDTO);
        if (dashboardConfigDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        DashboardConfigDTO result = dashboardConfigService.save(dashboardConfigDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, dashboardConfigDTO.getId().toString()))
            .body(result);
    }

    @GetMapping("/dashboard-configurations")
    @Timed
    public ResponseEntity<List<DashboardConfigDTO>> getAllDashboardConfigs(Pageable pageable) {
        log.debug("REST request to get a page of DashboardConfigs");
        Page<DashboardConfigDTO> page = dashboardConfigService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/dashboard-configurations");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    @GetMapping("/dashboard-configurations/{id}")
    @Timed
    public ResponseEntity<DashboardConfigDTO> getDashboardConfig(@PathVariable String id) {
        log.debug("REST request to get DashboardConfiguration : {}", id);
        Optional<DashboardConfigDTO> dashboardConfigDTO = dashboardConfigService.findOne(id);
        return ResponseUtil.wrapOrNotFound(dashboardConfigDTO);
    }

    @GetMapping("/dashboard-configurations/findByName/{name}")
    @Timed
    public String findByName(@PathVariable String name) {
        Optional<DashboardConfigDTO> dashboardConfigDTO = dashboardConfigService.findByName(name);
        return JSON.toJSONString(dashboardConfigDTO);
//        return ResponseUtil.wrapOrNotFound(dashboardConfigDTO);
    }

    @DeleteMapping("/dashboard-configurations/{id}")
    @Timed
    public ResponseEntity<Void> deleteDashboardConfig(@PathVariable String id) {
        log.debug("REST request to delete DashboardConfiguration : {}", id);
        dashboardConfigService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    @DeleteMapping("/dashboard-configurations/deleteByName/{name}")
    @Timed
    public ResponseEntity<Void> deleteByName(@PathVariable String name) {
        dashboardConfigService.deleteByName(name);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, name)).build();
    }

    // 获取语音播报token
    @GetMapping("/dashboard-configurations/getVoiceToken")
    public String getVoiceToken() {
        User user = userService.getUserWithAuthorities();
        if (user == null) {
            throw new BadCredentialsException("Invalid token");
        }
        JSONObject result = dashboardConfigService.getVoiceToken();
        return JSON.toJSONString(result);
    }
}
